<?php

namespace Model;

class Push extends \Lib\Model {
	private $_oChannel;
	public function init() {
		global $o;
		$sPath = $o->Config->get ( '3thlib.path' );
		require_once $sPath . '/BaiduPush/Channel.class.php';
		$this->_oChannel = new \Channel ( $o->Config->get ( 'push.ApiKey' ), $o->Config->get ( 'push.SecretKey' ) );
	}
	public function getBindList($iUserId) {
		if (! is_object ( $this->_oChannel )) {
			$this->init ();
		}
		$this->o->Debug->show ( $this->_oChannel->queryBindList ( $iUserId ) );
	}
	public function pushMessage() {
		if (! is_object ( $this->_oChannel )) {
			$this->init ();
		}
		$aMessageInfo = $this->o->DB->get ( 'push', array (
				'dateline' => 0 
		) );
		if (! $aMessageInfo) {
			$this->o->aError = array (
					'code' => 1,
					'message' => '没有需要发送的消息' 
			);
			return false;
		}
		$aMessage = array (
				'title' => $aMessageInfo ['title'],
				'description' => $aMessageInfo ['message'],
				'open_type' => 0,
				'pkg_name' => 'com.diypda.jy139' 
		);
		if (! $this->_oChannel->pushMessage ( 3, json_encode ( $aMessage ), 'msg_id_' . $aMessageInfo ['id'], array (
				'message_type' => 1 
		) )) {
			$this->o->aError = array (
					'code' => $this->_oChannel->errno (),
					'message' => $this->_oChannel->errmsg () 
			);
			$this->o->DB->update ( 'push', array (
					'dateline' => time () 
			), array (
					'id' => $aMessageInfo ['id'] 
			) );
			return false;
		} else {
			$this->o->DB->update ( 'push', array (
					'success' => 1,
					'dateline' => time () 
			), array (
					'id' => $aMessageInfo ['id'] 
			) );
			return true;
		}
	}
}